# -*- coding: latin-1 -*-
# Copyright (c) 2007-2009 Jorge Ortiz Romo <jortizromo@gmail.com>
#                         Freymam Vallejo Cuero <freturn@gmail.com>
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:

# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
# Import the module and instantiate a pygraph object

'''
Created on Dec 7, 2009

@author: Freymam Vallejo
@author: Jorge Ortiz
'''

from iasna_core.sna.common import IsConnected
from pygraph.algorithms.minmax import shortest_path

def diameter(gr):
    """
    function Diameter a graph

    @type gr:  graph
    @param gr: graph.

    @rtype: int.
    @return: it returns the maximum geodesic distance between a pair of nodes, that corresponds to the Diameter of the graph.
    """
    if IsConnected.is_connected(gr):
        
        #getting all nodes to get the distance between each one of them to the others
        nodes = gr.nodes()
        #initialize var that will save the maximum distance between a pair of nodes (The diameter of the graph)
        max_distance = 0
        for node in nodes:
            tuple_dicts = shortest_path(gr, node)
            for key in tuple_dicts[1].keys():
                if tuple_dicts[1][key] > max_distance:
                    max_distance = tuple_dicts[1][key]
        return max_distance
    else:
        return 'undefined'
